package com.googlecode.connectlet.util.db;

import java.io.Closeable;
import java.io.PrintStream;

public class DumpCallback implements RowCallback, Closeable {
	private static final int ROWS_PER_LINE = 256;

	private int i = 0;
	private PrintStream out;
	private String sql, format;
	private Object[] data;

	public DumpCallback(PrintStream out, String sql, String format, int columns) {
		this.out = out;
		this.sql = sql;
		this.format = format;
		data = new Object[columns];
	}

	@Override
	public boolean onRow(Row row) {
		if (i % ROWS_PER_LINE == 0) {
			if (i > 0) {
				out.println(";");
			}
			out.print(sql);
		} else {
			out.print(", ");
		}
		i ++;
		for (int j = 0; j < data.length; j ++) {
			Object o = row.get(j + 1);
			if (o != null && o instanceof String) {
				data[j] = ((String) o).replace("\\\\", "\\\\\\\\").
						replace("\\\'", "\\\\\\\'").replace("\\\"", "\\\\\\\"");
			} else {
				data[j] = o;
			}
		}
		out.printf(format, data);
		return true;
	}

	@Override
	public void close() {
		out.println(";");
	}
}